package com.turnengine.client.local.upkeep;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import com.turnengine.client.local.unit.bean.IUnit;
import com.turnengine.client.local.upkeep.bean.IUpkeep;
import com.turnengine.client.local.upkeep.bean.IUpkeepCondition;

public class UpkeepCache implements IUpkeepCache {

	private final Map<Integer, IUpkeepDefinition> idToDefinitionMap = new ConcurrentHashMap<Integer, IUpkeepDefinition>();

	@Override
	public void addUpkeeps(Collection<IUpkeep> upkeeps) {
		for (IUpkeep upkeep : upkeeps) {
			addUpkeep(upkeep);
		}
	}

	@Override
	public void addConditions(Collection<IUpkeepCondition> conditions) {
		for (IUpkeepCondition condition : conditions) {
			addCondition(condition);
		}
	}

	@Override
	public void addUpkeep(IUpkeep upkeep) {
		int upkeepId = upkeep.getUpkeepId();
		IUpkeepDefinition definition = idToDefinitionMap.get(upkeepId);
		if (definition != null) {
			throw new IllegalArgumentException("upkeep already defined for id=" + upkeepId);
		}
		definition = new UpkeepDefinition(upkeep);
		idToDefinitionMap.put(upkeepId, definition);
	}

	@Override
	public void addCondition(IUpkeepCondition condition) {
		IUpkeepDefinition definition = getDefinition(condition.getUpkeepId());
		definition.addCondition(condition);
	}

	@Override
	public List<IUpkeep> getUpkeeps() {
		List<IUpkeep> list = new ArrayList<IUpkeep>();
		for (IUpkeepDefinition definition : idToDefinitionMap.values()) {
			list.add(definition.getUpkeep());
		}
		return list;
	}

	@Override
	public List<IUpkeepCondition> getConditions() {
		List<IUpkeepCondition> list = new ArrayList<IUpkeepCondition>();
		for (IUpkeepDefinition definition : idToDefinitionMap.values()) {
			list.addAll(definition.getConditions());
		}
		return list;
	}

	@Override
	public IUpkeepDefinition getDefinition(int unitId) {
		IUpkeepDefinition definition = idToDefinitionMap.get(unitId);
		if (definition == null) {
			throw new IllegalArgumentException("upkeep not defined for id=" + unitId);
		}
		return definition;
	}

	@Override
	public IUpkeepDefinition getDefinition(IUnit unit) {
		return getDefinition(unit.getId());
	}

	@Override
	public IUpkeepDefinition getDefinition(IUpkeep upkeep) {
		return getDefinition(upkeep.getUpkeepId());
	}

}
